//
// Created by Administrator on 2021/3/1.
//

#include "console_ui.h"
#include <stdlib.h>
#include <stdio.h>

UIContext *ui_context;

static void DisplayTextWithFile(char *text){
  //向目标 `ui_context->text_displayer` 写入一行 `text`
  fputs(text, ui_context->text_displayer); //puts会自动加上换行 但fputs不会
  fputc('\n', ui_context->text_displayer);

  fflush(ui_context->text_displayer);
}

static void ConsoleMain(){
  int next_input = getchar();
  while (next_input != EOF && next_input != 'q' && next_input != 'Q') {
    HandleInput(ui_context->context, next_input);
    next_input = getchar();
  }

  puts("Thank u!");
}

static void InitConsole(){
  ui_context = malloc(sizeof(UIContext));
  ui_context->text_displayer = stdout;
  ui_context->context = CreateCalcContext();
  ui_context->context->display_text = DisplayTextWithFile;
}

static void DestroyConsole(){
  DestroyCalcContext(&ui_context->context);
  free(ui_context);
  ui_context = NULL;
}

int RunConsoleUI(int argc, char *argv[]){
  InitConsole();

  ConsoleMain();

  DestroyConsole();
}
